class LoginController < ApplicationController
  before_filter :logevent, :authorize, :except => :login
  layout "admin"
  
  def index
end

  def add_user
    if request.get?
      @user = User.new
    else
      @user = User.new(params[:user])
      if @user.save
        flash[:notice] = "User #{@user.username} created"
        redirect_to :action => 'list_users'
      else
        flash[:notice] = "User #{@user.username} creation failed"
        render :action => 'add_user'
      end
    end
  end

  def login
    if request.get?
      session[:user_id] = nil
      @user = User.new
    else
      @user = User.new(params[:user])
      logged_in_user = @user.try_to_login
      
      if logged_in_user
        session[:user_id] = logged_in_user.id
        session[:admin_user] = logged_in_user.isadmin
        redirect_to_index("index")
      else
        flash[:notice] = "Invalid Username/Password. Please try again "
      end
    end
  end
  
  def logout
   session[:user_id] = nil
   flash[:notice] = "Logged out"
   redirect_to(:action => "login")
  end

  def delete_user
    id = params[:id]
    if id && user = User.find(id)
      begin
        user.destroy
        flash[:notice] = "User #{user.username} deleted"
      rescue
        flash[:notice] = "Can not delete #{user.username}"
      end
    end
    redirect_to :action => 'list_users'
  end

  def list_users
    @user_pages, @users = paginate :users, :per_page => 10
  end
end
